import React from 'react';
import * as Select from '@radix-ui/react-select';
import styles from './index.module.scss';
import classNames from 'classnames';
import { update } from '@/utils/immutableUtil';
import { Search, X } from 'lucide-react';
import { applied_list } from '@/api/ai';
import debounce from 'lodash/debounce';

class Comp extends React.Component {
  state = {
    selectedVal: null,
    searchQuery: '',
    list: [],
  };

  inputRef = React.createRef();

  componentDidMount = () => {
    setTimeout(() => {
      this.inputRef?.current?.focus();
    }, 0);
    this.setState({list:this.props.mcpList})
  };

  componentWillUnmount() {
    // 组件卸载时取消防抖，防止内存泄漏
    this.debouncedSearchRequest.cancel && this.debouncedSearchRequest.cancel();
  }
  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);

  handleItemSelect = (value) => {
    const { onSelect } = this.props;
    const selectedItem = this.state.list.find(
      (item) => String(item.server_name) === value,
    );

    if (selectedItem && onSelect) {
      onSelect(selectedItem.server_name,selectedItem);
    }

    this.setState({ selectedVal: value });
  };

  // 用于防抖的实际请求逻辑
  _searchRequest = async (searchQuery) => {
    if(!searchQuery){
      this.setState({list:this.props.mcpList})
      return 
    }
    var rs = await applied_list({
      server_name: searchQuery,
    });

    if (rs.data?.code == 200) {
      var data = rs.data.data;
      this.setState({ list: data }, () => {
        setTimeout(() => {
          this.inputRef.current.focus();
        }, 0);
      });
      console.log(data);
    }
  };

  // 防抖函数（300ms，可根据需求调整）
  debouncedSearchRequest = debounce(this._searchRequest, 300);

  handleSearchChange = (e) => {
    var searchQuery = e.target.value;
    this.setState({ searchQuery });
    this.debouncedSearchRequest(searchQuery);
  };

  handleOpenChange = (open) => {
    const { onOpenChange } = this.props;

    if (open && this.inputRef.current) {
      // Use a small timeout to ensure the dropdown is fully rendered
      setTimeout(() => {
        this.inputRef.current.focus();
      }, 50);
    }

    // Notify parent component about open state change
    if (onOpenChange) {
      onOpenChange(open);
    }
  };

  handleCloseClick = (e) => {
    e.stopPropagation();
    this.handleOpenChange(false);
  };

  render() {
    const { open } = this.props;
    const { selectedVal, searchQuery, list } = this.state;

    return (
      <div className={styles.container}>
        <Select.Root
          value={selectedVal}
          open={open}
          onValueChange={this.handleItemSelect}
          onOpenChange={this.handleOpenChange}
        >
          <Select.Trigger aria-label="Select plugin"></Select.Trigger>

          <Select.Portal>
            <Select.Content
              className={styles.content}
              position="popper"
              sideOffset={8}
              align="start"
              side="top"
            >
              <div className={styles.searchContainer}>
                <Search size={14} className={styles.searchIcon} />
                <input
                  ref={this.inputRef}
                  type="text"
                  className={styles.searchInput}
                  placeholder="Search Mcp Servers..."
                  value={searchQuery}
                  onChange={this.handleSearchChange}
                  onClick={(e) => e.stopPropagation()}
                />
                <button
                  className={styles.closeButton}
                  onClick={this.handleCloseClick}
                  aria-label="Close dropdown"
                >
                  <X size={14} />
                </button>
              </div>

              <Select.Viewport>
                <div className={styles.pluginRow}>
                  {list.length > 0 ? (
                    list.map((item) => (
                      <Select.Item
                        key={String(item.server_name)}
                        value={String(item.server_name)}
                        className={classNames(styles.item, {
                          [styles.selected]: selectedVal === item.server_name,
                        })}
                      >
                        <div className={styles.pluginName}>
                          {item.server_name}
                        </div>
                      </Select.Item>
                    ))
                  ) : (
                    <div className={styles.noResults}>
                      {/* No servers found */}
                    </div>
                  )}
                </div>
              </Select.Viewport>
            </Select.Content>
          </Select.Portal>
        </Select.Root>
      </div>
    );
  }
}

export default Comp;
